package thread;

import java.util.concurrent.PriorityBlockingQueue;

//创建一个类 表示一个任务
class Mytask implements Comparable<Mytask>{
    //任务具体要干嘛
    private Runnable runnable;
    //任务具体啥时候干
    private long time;
    //delay是一个间隔 不是真正的时间戳
    public Mytask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }

    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(Mytask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer{
    //定时器内部要能够存放多个任务
    //此处的队列要考虑线程安全问题  可能在多个线程里进行注册任务.
    // 同时还有一个专门的线程来取任务执行.此处的队列就需要注意线程安全问题
    private PriorityBlockingQueue<Mytask> queue = new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable,long delay){
        Mytask mytask = new Mytask(runnable,delay);
        queue.put(mytask);
    }

    public MyTimer(){
        Thread t = new Thread(() -> {
            while (true){
                try {
                    //先取出队首元素
                    Mytask mytask = queue.take();
                    //再比较看一下当前这个任务时间到了没
                    long curTime = System.currentTimeMillis();
                    if(curTime < mytask.getTime()){
                        //时间没到，把任务再塞回到队列中
                        queue.put(mytask);
                    }else{
                        //时间到了执行这个任务
                        mytask.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

public class demo24 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer~~");
            }
        },3000);
        System.out.println("main");
    }
}
